#ifndef F_CPU
#define F_CPU 1000000UL
#endif

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#include <string.h>

#include "i2cmaster.h"
#include "luart.h"




#define USART_BUFFER_SIZE 128
#define INPUT_BUFFER_SIZE 128
#define DELAY_MS 1000

char DEVICE_ADDR = 0b1001101;
char DATA_REGISTER = 0b0;
char i2c_data;


unsigned char i2c_check_addr(unsigned char dev_addr);
unsigned char i2c_read_byte (unsigned char dev_addr, unsigned char reg);
unsigned int str_to_hex(const char* str);
void execute(const char* command);


char usart_data[USART_BUFFER_SIZE];
char input_buffer[INPUT_BUFFER_SIZE];


ISR(USART_RXC_vect)
{
	char character = UDR;

	if (character == UART_NEWLINE)
	{
		execute(input_buffer);
		input_buffer[0] = '\0';
	}
	else
	{
		// can be optimized
		int oldlen = strlen(input_buffer);
		input_buffer[oldlen++] = character;	
		input_buffer[oldlen] = '\0';
	}
}

int main(void)
{
    i2c_init();
	usart_init();
	
	sei();
	
	while (1)
	{
		_delay_ms(DELAY_MS);
	}
	

	//while (1)
	//{
		////i2c_data = i2c_read_data();
		//sprintf(usart_data, "Register: %i Data: %i", DATA_REGISTER, i2c_data);
		//usart_println(usart_data);
		//
		//_delay_ms(DELAY_MS);
	//}	
}

// 0 if a device with such address exists, 1 if it does not exist
unsigned char i2c_check_addr(unsigned char dev_addr)
{
	return i2c_start((dev_addr << 1) + I2C_WRITE);
}

unsigned char i2c_read_byte(unsigned char dev_addr, unsigned char reg)
{
	unsigned char result;
	
	// start writing
	i2c_start((dev_addr << 1) + I2C_WRITE); // we're going to write
	i2c_write(reg); // selecting a register
	// stop writing
	
	// start reading
	i2c_rep_start((dev_addr << 1) + I2C_READ); // we're going to read
	result = i2c_readNak();
	i2c_stop();
	// stop reading
		
	return result;
}

unsigned int str_to_hex(const char* str)
{
	unsigned int res = 0;
	
	sscanf(str, "%x", &res);
	
	return res;
}

void execute(const char* command)
{
	sprintf(usart_data, "Your input is equal to: %i.", str_to_hex(command));
	usart_println(usart_data);
}
